package com.yunshipei.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;

import com.yunshipei.EnterApplication;

import org.chromiun.ui.widget.Toast;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.HashSet;

/**
 * Created by cike on 16/1/28.
 */
public class FileUtils {
    private static String[] ftArrary = {".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".mp3",
            ".wma", ".wav", ".ape", ".rm", ".rmvb", ".wmv", ".avi", ".mp4", ".3gp", ".mkv", ".zip", ".bmp", ".jpg", ".jpeg", ".png", ".gif"};
    private static HashSet<String> ftType = new HashSet<>(Arrays.asList(ftArrary));

    public static String ReadTxtFile(String strFilePath) {
        String path = strFilePath;
        String content = ""; //文件内容字符串
        //打开文件
        File file = new File(path);
        //如果path是传递过来的参数，可以做一个非目录的判断
        if (file.isDirectory()) {
            Log.d("TestFile", "The File doesn't not exist.");
        } else {
            try {
                InputStream instream = new FileInputStream(file);
                if (instream != null) {
                    InputStreamReader inputreader = new InputStreamReader(instream);
                    BufferedReader buffreader = new BufferedReader(inputreader);
                    String line;
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content += line + "\n";
                    }
                    instream.close();
                }
            } catch (java.io.FileNotFoundException e) {
                Log.d("TestFile", "The File doesn't not exist.");
            } catch (IOException e) {
                Log.d("TestFile", e.getMessage());
            }
        }
        return content;
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath, fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }


    /**
     * 图片Uri转化为Path
     *
     * @param uri
     * @return
     */

    public static String getPathbyUri(Uri uri) {
        String path = "";
        if ("file".equals(uri.getEncodedPath())) {
            path = uri.getEncodedPath();
            if (!TextUtils.isEmpty(path)) {
                path = Uri.decode(path);
                ContentResolver cr = EnterApplication.getApp().getApplicationContext().getContentResolver();
                StringBuffer buffer = new StringBuffer();
                buffer.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'")
                        .append(")");
                Cursor cursor = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.ImageColumns._ID,
                        MediaStore.Images.ImageColumns.DATA}, buffer.toString(), null, null);
                int dataIndex = 0;
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    path = cursor.getString(dataIndex);
                }
                if (!TextUtils.isEmpty(path)) {
                    return path;
                }
            }
        } else if ("content".equals(uri.getScheme())) {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = EnterApplication.getApp().getApplicationContext().getContentResolver()
                    .query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(columnIndex);
            }
        }
        return path;
    }

    public static boolean haveFile(File file) {
        if (file.exists() && getFileSize(file) > 0) {
            return true;
        }
        return false;
    }

    public static boolean haveFile(String path) {
        File file = new File(path);
        return haveFile(file);
    }

    public static boolean haveFile(Uri uri) {
        File file = new File(getPathbyUri(uri));
        return haveFile(file);
    }


    public static long getFileSize(File file) {
        long size = 0;
        if (!file.isDirectory()) {
            try {
                FileInputStream fileInput = new FileInputStream(file);
                try {
                    size = fileInput.available();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileInput.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return size;
    }

    /**
     * @param file
     * @param type type == 1 B,type == 2 KB, type == 3 MB, type == 4 GB
     * @return
     */
    public static long getFileSize(File file, int type) {
        long size = getFileSize(file);
        switch (type) {

            case 2:
                size = size / 1024;
                break;
            case 3:
                size = size / 1048576;
                break;
            case 4:
                size = size / 1073741824;
                break;
            default:
                break;
        }
        return size;
    }

    public static boolean writeToFile(String savePath, String fileName, InputStream is) {
        File targetFile = makeFilePath(savePath, fileName);
        OutputStream os = null;
        try {
            os = new FileOutputStream(targetFile);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                assert is != null;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                assert os != null;
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void deleteDir(File file) {
        if (file.exists() && file.isFile()) {
            file.delete();
        } else if (file.exists() && file.isDirectory()) {
            for (File subFile : file.listFiles()) {
                if (subFile.exists() && subFile.isDirectory()) {
                    deleteDir(subFile);
                } else {
                    subFile.delete();
                }
            }
            file.delete();
        }
    }

    public static String getFileType(File f) {
        /**
         * 识别文件的类型
         * @param f
         * @return
         */
        String end = f.getName().substring(f.getName().lastIndexOf(".") + 1,
                f.getName().length()).toLowerCase();
        String type = "";
        if (end.equals("mp3") || end.equals("aac") || end.equals("aac")
                || end.equals("amr") || end.equals("mpeg") || end.equals("mp4")) {
            type = "audio";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) {
            type = "image";
        } else if (end.equals("doc") || end.equals("docx") || end.equals("pdf")
                || end.equals("txt")) {
            type = "application/msword";
            return type;
        } else {
            type = "*";
        }
        type += "/*";
        return type;
    }

    public static boolean fileType(File file) {
        int index = file.getName().lastIndexOf(".");
        if (index >= 0) {
            String end = file.getName().substring(file.getName().lastIndexOf("."),
                    file.getName().length()).toLowerCase();
            return ftType.contains(end);
        }
        return false;
    }

    //Enterplorer图片缓存路径
    public static String getEnterImgCachePath() {
        String path = "/yunshipei/pic";
        return CheckSdCard.getInstance().Mkdir(path).toString();
    }

    @NonNull
    public static String makeFilePath(File file) {
        if (!file.exists() || file.isDirectory()) {
            file.mkdirs();
        }
        return file.getPath();
    }

    public static String getFileName(String path) {
        if (TextUtils.isEmpty(path))
            return null;
        int start = path.lastIndexOf("/");
        int end = path.lastIndexOf(".");
        if (start != -1 && end != -1 && end > start)
            return path.substring(start + 1, end);
        return null;
    }

    public static String readAssertResource(Context context, String strAssertFileName) {
        AssetManager assetManager = context.getAssets();
        String strResponse = "";
        try {
            InputStream ims = assetManager.open(strAssertFileName);
            strResponse = getStringFromInputStream(ims);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return strResponse;
    }

    private static String getStringFromInputStream(InputStream a_is) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(a_is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
        return sb.toString();
    }

    public static byte[] toByteArray(String filePath) throws IOException {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
        }
        return baos.toByteArray();
    }



    /**
     * 发动邮件
     * @param context
     */
    public static void sendEmail(Context context) {
//        Intent intent = new Intent(Intent.ACTION_SEND);
//        intent.setType("plain/text");
//        intent.putExtra(Intent.EXTRA_EMAIL, "");
//        intent.putExtra(Intent.EXTRA_SUBJECT, "");
//        intent.putExtra(Intent.EXTRA_TEXT, "");
//        try {
//            if (!(context instanceof Activity)) {
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            }
//            context.startActivity(intent);
//        } catch (android.content.ActivityNotFoundException ex) {
//            Toast.makeText(context, "未安装邮箱应用！", Toast.LENGTH_SHORT).show();
//        }


        Uri uri = Uri.parse("mailto:"+"me@abc.com");
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE, uri);
        //intent.putExtra(Intent.EXTRA_CC, email); // 抄送人
        // intent.putExtra(Intent.EXTRA_SUBJECT, "这是邮件的主题部分"); // 主题
        // intent.putExtra(Intent.EXTRA_TEXT, "这是邮件的正文部分"); // 正文
        context.startActivity(Intent.createChooser(intent, "请选择邮件类应用"));


    }

}
